package com.gmrz.uaf.servlet.v1.handler;

import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.uaf.protocol.v1.json.UAFSchemaBuilder;
import com.gmrz.uaf.protocol.v1.processor.UAFUpdateCertStatusProcessor;
import com.gmrz.uaf.server.ServerContext;
import com.gmrz.uaf.servlet.v1.request.ActivateCertContext;
import com.gmrz.uaf.servlet.v1.request.ReceiveReqPayload;
import com.gmrz.uaf.servlet.v1.response.FidoRespPayload;
import com.gmrz.uaf.servlet.v1.validation.PayloadValidationException;
import com.gmrz.uaf.servlet.v1.validation.RestValidator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Type;
import java.util.List;

/**
 *
 */
public class UAFActivateCertHandler extends UAFBaseHandler {

    private static final Logger LOG = LogManager.getLogger(UAFActivateCertHandler.class);


    /**
     * @param request
     */
    public String activateCert(String request) {

        LOG.info("[/cert/activate][begin]");
        ServerContext.getServerContext().getFidoLog().setRequest(request);
        FidoRespPayload<List<String>> respPayload = new FidoRespPayload<List<String>>();
        String response = null;
        try {


            Gson gson = UAFSchemaBuilder.getGson();
            Type reqType = new TypeToken<ReceiveReqPayload<ActivateCertContext>>() {
            }.getType();

            ReceiveReqPayload<ActivateCertContext> reqPayload = gson.fromJson(request, reqType);
            ActivateCertContext context = reqPayload.getContext();
            logRequest(request, reqPayload.getContext().getTransNo(), context.getUserName(),
                    context.getAppID(), context.getAuthType(),context.getTransType(), Constants.Method.ACTIVATE_CERT);
            validate(reqPayload);

            UAFUpdateCertStatusProcessor processor = GuiceUtil.getProcessorInjector().
                    getInstance(UAFUpdateCertStatusProcessor.class);
            // hash 用户名
            String hashedUserName = generateHashedUserName(context.getUserName(), context.getRf1(), context.getRf2());

            int n = processor.activateCert(context.getAppID(),hashedUserName,context.getAuthType(),context.getTransType(),context.getActivateType(),context.getActivateAppID(),context.getDevices());
            if(n > 0) {
                respPayload.setStatusCode(1200);
                respPayload.setDescription("OK");
            }else {
                respPayload.setStatusCode(1400);
                respPayload.setDescription("Failed to activate certificate .");
            }
            return gson.toJson(respPayload);
        } catch (Exception ex) {
            LOG.error(ex);
            response = buildFidoRespFromException(respPayload, ex);
        }
        LOG.info("[/cert/activate][end]");
        return response;
    }

    private void validate(ReceiveReqPayload<ActivateCertContext> reqPayload)
            throws PayloadValidationException {
        if ((reqPayload == null) || (reqPayload.getContext() == null)) {
            throw new PayloadValidationException("context", RestValidator.VALIDATION_ERROR.EMPTY);
        }
        if (null == reqPayload.getContext().getDevices()) {
            throw new PayloadValidationException("devices", RestValidator.VALIDATION_ERROR.EMPTY);
        }
        RestValidator.validate("transNo", reqPayload.getContext().getTransNo());
        RestValidator.validate("userName", reqPayload.getContext().getUserName());
        RestValidator.validate("rf1", reqPayload.getContext().getRf1());
        RestValidator.validate("rf2", reqPayload.getContext().getRf2());
        RestValidator.validate("appID", reqPayload.getContext().getAppID());
        RestValidator.validate("authType", reqPayload.getContext().getAuthType());
        RestValidator.validate("transType", reqPayload.getContext().getTransType());
        RestValidator.validate("deviceID", reqPayload.getContext().getDevices().getDeviceID());
        RestValidator.validate("activateType", reqPayload.getContext().getActivateType());
        RestValidator.validate("activateAppID", reqPayload.getContext().getActivateAppID());
    }
}


